package com.xiaoshuidi.cloud.module.bpm.job.xxljob;

import cn.hutool.core.util.ObjectUtil;
import com.xiaoshuidi.cloud.framework.tenant.core.aop.TenantIgnore;
import com.xiaoshuidi.cloud.framework.tenant.core.job.TenantJob;
import com.xiaoshuidi.cloud.module.bpm.dal.dataobject.swo.SwoTicketDO;
import com.xiaoshuidi.cloud.module.bpm.dal.mysql.swo.SwoTicketMapper;
import com.xiaoshuidi.cloud.module.contract.api.ContractRentOrderApi;
import com.xiaoshuidi.cloud.module.contract.vo.GetSowTicketOrderByIdsReq;
import com.xiaoshuidi.cloud.module.contract.vo.RentOrderSowTicketVO;
import com.xxl.job.core.handler.annotation.XxlJob;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.concurrent.atomic.AtomicReference;
import java.util.stream.Collectors;

/**
 * 同步所有工单的账单金额到bpm库中
 */
@Slf4j
@Component
@TenantJob
public class AmountOfRepairsJob {

    @Resource
    private SwoTicketMapper swoTicketMapper;
    @Resource
    private ContractRentOrderApi contractRentOrderApi;

    /***
     * 同步所有工单的账单金额
     * 7.0.9 版本上线时执行一次
     */
    @XxlJob("sync-amount-of-repairs")
    public void syncAmountOfRepairs() {
        // 查询所有工单
        log.info("[同步所有工单的账单金额Job]--开始");
        List<SwoTicketDO> swoTicketDOS = swoTicketMapper.selectList();
        List<SwoTicketDO> updateList = new ArrayList<>();
        log.info("[同步所有工单的账单金额Job]--共{}个工单", swoTicketDOS.size());
        List<Long> swoTicketIds = swoTicketDOS.stream().map(SwoTicketDO::getId).collect(Collectors.toList());
        // 所有工单的账单
        Map<Long, List<RentOrderSowTicketVO>> swoTicketOrderMap =
                contractRentOrderApi.getSowTicketOrderByIds(new GetSowTicketOrderByIdsReq().setSwoTicketIds(swoTicketIds)).getCheckedData();
        swoTicketDOS.forEach(swoTicketDO -> {
            if (!swoTicketOrderMap.containsKey(swoTicketDO.getId())) {
                return;
            }
            List<RentOrderSowTicketVO> orderList = swoTicketOrderMap.get(swoTicketDO.getId());
            if (ObjectUtil.isNotEmpty(orderList)) {
                swoTicketDO.setNeedPay(true);
            }else {
                swoTicketDO.setNeedPay(false);
            }
            AtomicReference<BigDecimal> decimal = new AtomicReference<>(BigDecimal.ZERO);
            // 所有账单的总金额
            orderList.forEach(order -> {
                decimal.set(decimal.get().add(order.getTotalAmount()));
            });
            swoTicketDO.setAmountOfRepairs(decimal.get());
            updateList.add(swoTicketDO);
        });
        swoTicketMapper.updateBatch(updateList, updateList.size());
        log.info("[同步所有工单的账单金额Job]--结束");
    }

}
